import vue from '@vitejs/plugin-vue'
import path from 'path'
import { UIViteAutoImport } from 'ui-vite/src/autoimport'
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { viteDef } from 'vite-var'

import { FileUtil } from 'tools-mock'
// https://vitejs.dev/config/
const buildArr = [
    'tools-javascript',
    'tools-css',
    'tools-vue3',
    'ui-vite',
    'axios',
    'vue-router',
    'element-plus',
    'vue+runtime',
    'vue'
]
function extractPackageName(input: string): string | null {
    const packageNameRegex = /^(@?[^@]+(?:\+[^@]+)?)(?:@[\d.]+)?/
    const match = input.match(packageNameRegex)
    if (match) {
        return match[1]
    }
    return null
}

export default defineConfig(({ command, mode }) => {
    return {
        resolve: {
            alias: {
                '~/': `${path.resolve(__dirname, 'src')}/`
            }
        },
        plugins: [
            viteDef(mode),
            vue(),
            UIViteAutoImport({
                isBuild: true,
                include: ['VSwitch', 'VSwitchItem']
            }),

            AutoImport({
                dts: './build/auto/auto-imports.d.ts',
                resolvers: [ElementPlusResolver()]
            }),
            Components({
                dts: './build/auto/components.d.ts',
                resolvers: [ElementPlusResolver()]
            }),
            {
                name: 'end',
                async closeBundle() {
                    const htmlDir = path.join(__dirname, './build')
                    FileUtil.deleteFileOrDirectory(htmlDir)
                }
            }
        ],
        server: {
            host: '0.0.0.0',
            port: 9650,
            open: false,
            https: false
        },
        build: {
            assetsDir: 'static_app',
            minify: 'terser',
            cssCodeSplit: true, // 如果设置为false，整个项目中的所有 CSS 将被提取到一个 CSS 文件中
            reportCompressedSize: false,
            terserOptions: {
                compress: {
                    // warnings: false,
                    drop_console: true, // 打包时删除console
                    drop_debugger: true, // 打包时删除 debugger
                    pure_funcs: ['console.log']
                },
                output: {
                    // 去掉注释内容
                    comments: true
                }
            },
            rollupOptions: {
                output: {
                    manualChunks(id) {
                        if (id.includes('node_modules')) {
                            const arr = id.toString().split('node_modules/')[1].split('/')
                            let npmName: any = arr[0].indexOf('pnpm') != -1 ? arr[1] : arr[0]
                            npmName = extractPackageName(npmName)
                            for (let i = 0; i < buildArr.length; i++) {
                                const key = buildArr[i]
                                if (npmName.indexOf(key) != -1) return key
                            }
                            return '_vendor'
                        }
                    }
                }
            }
        }
    }
})
